<?php

namespace Aoe\Emulator\Schema\Element;


use Aoe\Emulator\Ifc\Key;
use Aoe\Emulator\Ifc\Type;
use Aoe\Emulator\Schema\Model;
use Aoe\Util\Manager\NamedCollection;
use Exception;

/**
 * # 元素组
 *
 * @extends NamedCollection<Independent>
 */
class Elements extends NamedCollection
{
    public function __construct(array $defs, protected Model $model)
    {
        $elements = [];
        foreach ($defs as $def) if (isset($def[Key::NAME])) $elements[$def[Key::NAME]] = $def;
        parent::__construct($elements);

        // 增加ID项
        try {
            $this->get(Type::ID);
            $this->get(Type::STATUS);
            $this->get(Type::OWNER);
            $this->get(Type::CREATE);
            $this->get(Type::UPDATE);
            if ($model->isTree() && !$this->model->useJson()) $this->get(Type::PID);
        } catch (Exception) {}
    }

    protected function create_object($name): Independent
    {
        $key = strtolower($name);
        $schema = $this->_make_element_schema($name, $this->named_items->get($key, []));

        return isset($schema[Key::RELATION]) ?
            new Relation($schema, $name, $this->model) :
            new Element($schema, $name, $this->model);
    }

    private function _make_element_schema(string $name, ?array $schema = []): ?array
    {
        $r = Type::defaultDefinition($name);
        if ($r) return $r;

        $adapter = $this->model->group->adapter;
        return $adapter ? $adapter->mixinElementPreset($schema) : $schema;
    }
}